package com.link.server.ws;

// WebSocketFrameHandler.java

import com.link.common.core.SpringContextUtil;
import com.link.common.packet.RequestOperate;
import com.link.server.ws.handle.HandlerManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketFrameHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws  Exception {
        // 只处理文本帧
        if (frame instanceof BinaryWebSocketFrame) {

            var startTime= System.currentTimeMillis();
            // 处理二进制消息
            ByteBuf packet =  frame.content();


            RequestOperate type = RequestOperate.of(packet.readInt());


            // 获取处理器并执行
            HandlerManager handlerManager = SpringContextUtil.getBean(HandlerManager.class);
            handlerManager.invoke(type, packet, ctx);



            System.out.println("处理耗时："+(System.currentTimeMillis()-startTime)+"ms");

        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {

        try {
            // 添加连接到通道管理
            WebSocketChannel.add(ctx.channel().id().asLongText(), ctx);
            logger.info("WebSocket 连接成功，Session ID: {}", ctx.channel().id().asLongText());
        } catch (Exception e) {
            logger.error("连接管理异常：{}", e.getMessage());
        }
        System.out.println("Client connected: " + ctx.channel().id());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        try {
            // 从通道管理中移除连接
            WebSocketChannel.remove(ctx.channel().id().asLongText());
            logger.info("WebSocket 连接关闭，Session ID: {}", ctx.channel().id().asLongText());
        } catch (Exception e) {
            logger.error("连接关闭异常：{}", e.getMessage());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}